<?php
namespace Client\Table;

use Zend\Db\Sql\Select;
use Zend\Paginator\Adapter\DbSelect;

use Zend\Paginator\Paginator;
use Zend\Db\Sql\Where;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Expression;

class UserTable extends CommonTable
{
    protected $table = 'hy_user';
    protected $id = 'user_id';
    
    public function find($type, $limit = 6) {
        
        $select = new Select();
        $select ->from($this->getTable())
        ->columns(array('banner_id', 'url', 'image'))
        ->where(array('type' => $type))
        ->order('banner_id DESC')
        ->limit($limit);
        $rowset = $this->selectWith($select);
        return $rowset->toArray();
    }

    public function recharge($amount,$user_id) {
        $set = array(
            'balance' => new Expression('balance+'.$amount)
        );
        return $this->update($set,array('user_id'=>$user_id));
    }
    
    public function updateUser($data,$where){
        if(empty($where)||empty($where['user_id'])){
                throw new \Exception("条件无效！");
        }

        if($data['username']){
                $set['user_name']=$data['username'];
        }

        if($data['image']){
                $set['user_thumb_image']=$data['image'];
        }

        return $this->update($set,array('user_id'=>$where['user_id']));
    }
    
    public function getUserInfo($user_id) {
        $select = new Select(array('u'=>$this->getTable()));
        $select->columns( array(
            "*"
        ));
        
        $select->join(
            array('o' => 'hy_organization'),
            'o.org_id = u.org_id',
            array('org_type','org_name') ,
            $select::JOIN_LEFT
            );
        
        $select->where(array('u.user_id'=>$user_id));
        
        $rowset = $this->selectWith($select);
        $row = $rowset->current();
        return $row;
    }
    
    public function getByOpenId($open_id) {
        $rowset = $this->select(array('open_id' => $open_id));
        $row = $rowset->current();
        return $row;
    }
    
    public function getByUid($user_uid) {
        $rowset = $this->select(array('user_uid' => $user_uid));
        $row = $rowset->current();
        return $row;
    }
}